const api = require('@/utils/request.js');
export default {
  data() {
    return {
      globalData: getApp().globalData,
      contentWithFooterStyle: '',
      bottomHeight: 68,
      showFixedBottom: false,
      lineNum: 1,
      hasBottom: false
    };
  },
  created() {
    let t = this;
    this.bottomHeightChange();
    if (!this.globalData.systemInit) {
      let menuButtonInfo = uni.getMenuButtonBoundingClientRect(); //获取菜单按钮（右上角胶囊按钮）的布局位置信息。坐标信息以屏幕左上角为原点。
      uni.getSystemInfo({
        //获取系统信息
        success: res => {
          t.globalData.fontsize = res.screenWidth / 430;
          t.globalData.pageHeightProportion = res.screenHeight / 932;
          let navBarHeight = (menuButtonInfo.top - res.statusBarHeight) * 2 + menuButtonInfo.height;
          let navBarInfo = { height: navBarHeight, paddingTop: menuButtonInfo.top - res.statusBarHeight, paddingBottom: menuButtonInfo.top - res.statusBarHeight };
          const safeAreaBottom = res.safeAreaInsets.bottom === 0 ? 20 : res.safeAreaInsets.bottom;
          const customizeContentHeight = res.screenHeight - res.statusBarHeight - navBarHeight - safeAreaBottom; // 屏幕高度 - 胶囊 - 表头
          const customizeHeaderHeight = res.statusBarHeight + navBarHeight;
          const customizeInfo = { safeAreaBottom, customizeContentHeight, customizeHeaderHeight };
          t.globalData.customizeInfo = customizeInfo;
          let mainStyle = `padding: 0 0 ${res.safeAreaInsets.bottom}rem 0; box-sizing: border-box;height:100%;overflow: hidden;`;
          let navStyle = `padding-top: ${res.statusBarHeight}rem; box-sizing: border-box;background:#FF7C00;`;
          let contentStyle = `padding: 0;box-sizing: border-box;height:calc(100% - ${res.statusBarHeight + navBarHeight}rem);overflow: auto;`;
          let contentStyle1 = `padding: 0;box-sizing: border-box;height:calc(100% - ${res.statusBarHeight + navBarHeight}rem);`;
          let contentPaddingStyle = `padding: 0 0 ${res.safeAreaInsets.bottom}rem 0; box-sizing: border-box;height:calc(100% - ${res.statusBarHeight + navBarHeight}rem);overflow: hidden;`;
          t.globalData.systemInit = true;
          t.globalData.navBarInfo = navBarInfo;
          // 自定义头部及内容样式
          const customizeBarStyle = `z-index:999;padding: ${res.statusBarHeight}rem 0 0 0; box-sizing: border-box;height:${navBarHeight}rem;position:fixed;top:0;left:0;width: 100%;top: 0;left: 0;background-color:#FF7C00`; // 客制化 顶部胶囊高度和padding-top内容
          const customizeContentStyle = `padding-top:${res.statusBarHeight + navBarHeight}rem;`; // 客制化 content内容
          t.globalData.appStyle = {
            customizeBarStyle,
            customizeContentStyle,
            navStyle,
            mainStyle,
            contentStyle,
            contentStyle1,
            contentPaddingStyle,
            safeBottom: res.screenHeight - res.safeArea.bottom
          };
        },
        fail(err) {
          console.log(err);
        }
      });
    }
  },
  mounted() {
    wx.showShareMenu({ withShareTicket: false, menus: ['shareAppMessage', 'shareTimeline'] });
  },
  methods: {
    appInit() {
      let t = this;
      return new Promise((resolve, reject) => {
        if (!this.globalData.apiInit) {
          // #ifdef MP-WEIXIN
          wx.login({
            success: async res => {
              if (res.code) {
                wx.request({
                  url: `${api.BASE_URL}/appUser/loginWx`,
                  data: { code: res.code },
                  method: 'GET',
                  header: { 'content-type': 'application/JSON', Authorization: uni.getStorageSync('Authorization') },
                  success: async resp => {
                    t.globalData.apiInit = true;
                    t.globalData.loginInfo = { ...resp.data.data };
                    if (resp.data.data.Authorization) {
                      t.globalData.Authorization = resp.data.data.Authorization;
                    }
                    await t.queryAllInfo();
                    resolve();
                  }
                });
              }
            },
            fail: res => {
              console.log('登录报错，可能不是开发者');
            }
          });
          // #endif
        } else {
          resolve();
        }
      });
    },
    async queryAllInfo() {
      await this.queryAll();
      await this.queryPlatformRule();
      await this.getUserInfo();
      await this.getUnCommentList();
      // 每五分钟查询一次
      this.getLastNotice();
      setInterval(() => {
        this.getLastNotice();
      }, 300000);
    },
    jumpToPage(url) {
      uni.navigateTo({ url });
    },
    bottomHeightChange() {
      let h = this.showFixedBottom ? 68 : 0;
      //没有bottom高度是68，有bottom一行是68+6+22，两行是68+6+22*2
      this.contentWithFooterStyle = `height: calc(100% - ${this.hasBottom ? h + 6 + 22 * this.lineNum : h}rem);`;
    },
    async queryAll() {
      let res = await api.request({ url: '/platformSetting/queryAll', method: 'GET' });
      if (res.data) {
        res.data.forEach(el => {
          this.globalData.platformInfo[el.settingKey] = el.settingValue;
        });
      }
      this.globalData.platformInfo.TEST = '没取到';
    },
    async getUserInfo() {
      let res = await api.request({ url: '/appUser/queryUserInfo', method: 'GET' });
      if (res.data) {
        this.globalData.userInfo = {
          ...res.data,
          shareId: this.globalData.userInfo.shareId,
          pointsBalance: Number(res.data.pointsBalance).toFixed(0),
          cardsBalance: Number(res.data.cardsBalance).toFixed(0),
          checkQty: Number(res.data.checkQty).toFixed(0),
          contactQty: Number(res.data.contactQty).toFixed(0)
        };
      }
    },
    // 查询通告信息
    async getLastNotice() {
      const res = await api.request({ url: '/notice/queryLatestNotice', method: 'GET' });
      if (res.data) {
        this.globalData.noticeInfo = res.data;
      }
      const res1 = await api.request({ url: '/notice/queryLatestNotice', method: 'GET' });
      if (res1.data) {
        this.globalData.noticeInfoNext = res1.data;
      }
    },
    // 查询待评价数据
    async getUnCommentList() {
      let res = await api.request({ url: '/appUser/queryMyUncommentContact', method: 'GET' });
      if (res.data) {
        this.globalData.MyUncommentContactObj = res.data;
      }
    },
    async queryPlatformRule() {
      let res = await api.request({ url: '/platformSetting/queryPlatformRule', method: 'get' });
      if (res.data) {
        res.data.forEach(el => {
          this.globalData.platformInfo[el.settingKey] = el.settingValue;
        });
      }
    },
    // 手机号隐藏中间内容展示
    displayPhoneNumber(phoneNumber) {
      if (phoneNumber) {
        return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      } else {
        return '';
      }
    },
    // 格式化时间展示
    // showType zh 带中文日期，en-纯数字
    formatDateTime(dateTimeString, showType) {
      // 解析日期时间字符串
      const dateTime = new Date(dateTimeString.replace(/-/g, '/'));
      // 获取年月日时分秒.isAlreadyAward == 1
      const year = dateTime.getFullYear();
      const month = String(dateTime.getMonth() + 1).padStart(2, '0'); // getMonth() 是从0开始的，所以要+1
      const date = String(dateTime.getDate()).padStart(2, '0');
      const hours = String(dateTime.getHours()).padStart(2, '0');
      const minutes = String(dateTime.getMinutes()).padStart(2, '0');
      // 格式化为你想要的格式
      const str = showType === 'zh' ? `${month}月${date}日 ${hours}:${minutes}` : `${year}-${month}-${date} ${hours}:${minutes}`;
      return str; // 注意：日期要减1，因为你是从2024-05-25开始，但想要5月24日
    },
    back() {
      uni.navigateBack({ delta: 1 });
    }
  }
};
